package com.cloud.sms.interceptor;

import com.cloud.commons.Result;
import com.cloud.commons.exception.BusinessException;
import com.cloud.commons.exception.ParamsValidateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 异常统一处理类
 *
 * @author tianchao
 */
@Component
@ControllerAdvice
@ResponseBody
@Slf4j
public class ExceptionInterceptor {

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result<?> exceptionHandler(HttpServletRequest req, Exception e) {
        log.info("调用异常", req.getRequestURI());
        Result<Object> result = new Result<Object>();
        Throwable throwable = e.getCause();
        if (null == throwable) {
            throwable = e;
        }
        
        if (throwable instanceof ParamsValidateException) {
            result.setCode(((ParamsValidateException) throwable).getCode());
            result.setMessage(e.getMessage());
        } else if (throwable instanceof BusinessException) {
            BusinessException businessException = (BusinessException) throwable;
            result.setCode(businessException.getCode());
            result.setMessage(businessException.getMessage());
        } else {
            result.setCode(1000);
            result.setMessage("系统异常");
        }
        log.error("服务异常:", e);
        return result;
    }

}
